package com.thkj.camera;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.thkj.common.config.AppConfig;
import com.thkj.common.util.RedisUtil;

import redis.clients.jedis.Jedis;

public class HikCamerasResoures {

    private static final String PARENTINDEXCODE = "-1";
    private static final String TREECODE = "0";
    private static ThreadLocal threadLocal = new ThreadLocal();


    public static Integer getCount(String districtName) {
        Integer total = 0;
        threadLocal.set(total);
        SearchCameraRequest searchCameraRequest = new SearchCameraRequest();
        searchCameraRequest.setPageNo(1);
        searchCameraRequest.setPageSize(1000);
//        searchCameraRequest.setSubRegion(true);
//        List<String> regionIndexCodes = new ArrayList<>();
//        regionIndexCodes.add("6d0d311e-a473-45c1-95c7-100f37ab6323");
//        searchCameraRequest.setRegionIndexCodes(regionIndexCodes);

        Jedis jedis = RedisUtil.getClient();
        ArtemisConfig.host = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret
        String subRegionsDataApi = "/artemis" + "/api/resource/v1/cameras";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", subRegionsDataApi);
            }
        };
        String body = JSON.toJSONString(searchCameraRequest);
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject response = JSONObject.parseObject(result);
        if (response != null && "SUCCESS".equals(response.getString("msg"))) {
            Integer c = (Integer) threadLocal.get();
            JSONObject jsonObject = response.getJSONObject("data");
            if (jsonObject.getInteger("total") == 1000) {
                Integer count = getCount("");
                threadLocal.set(c + count);
            } else {
                threadLocal.set(c + jsonObject.getInteger("total"));
            }
        }
        return (Integer) threadLocal.get();
    }

    /**
     * 获取组织结构 下的摄像头
     */
    public static List<Map> getHikOrigin() {
        Map<String, Object> paramsMap = new HashMap<>();
        List<String> paramsList = new ArrayList<>();
        paramsList.add("6d0d311e-a473-45c1-95c7-100f37ab6323");
        paramsMap.put("pageNo", "1");
        paramsMap.put("pageSize", "1000");
        paramsMap.put("isSubRegion", "true");
        paramsMap.put("parentIndexCodes", paramsList);
        paramsMap.put("resourceType", "region");
        String resultResponse = nodesByParams(paramsMap);

        JSONObject resultObj = JSONObject.parseObject(resultResponse);
        List<Map> list = new ArrayList<>();
        Map map = new HashMap();
        map.put("name", "阳东监管局");
        map.put("indexCode", "6d0d311e-a473-45c1-95c7-100f37ab6323");
        if (resultObj != null && "SUCCESS".equals(resultObj.getString("msg"))) {
            List<Map> childrenList = new ArrayList<>();
            List<Map> listMap = (List<Map>) resultObj.getJSONObject("data").get("list");
            for (Map childrenMap : listMap) {
                boolean available = (boolean) childrenMap.get("leaf");
                if (available) {
                    childrenList.add(childrenMap);
                }
            }

            map.put("children", childrenList);
        }
        list.add(map);
        return list;
    }

    /**
     * 获取第一级
     */
    public static List<Map> getHikDistrict() {
        SubRegionsRequest subRequest = new SubRegionsRequest();
        subRequest.setParentIndexCode(PARENTINDEXCODE);
        subRequest.setTreeCode(TREECODE);
        String oneRes = subRegions(subRequest);
        System.out.println("第一级=====" + oneRes);
        JSONObject response = JSONObject.parseObject(oneRes);
        List<Map> districtList = null;
        if (response != null && "SUCCESS".equals(response.getString("msg"))) {
            Map oneMap = ((List<Map>) response.get("data")).get(0);
            subRequest.setParentIndexCode(oneMap.get("indexCode").toString());
            subRequest.setTreeCode(oneMap.get("treeCode").toString());
            String twoRes = subRegions(subRequest);
            JSONObject country = JSONObject.parseObject(twoRes);
            if (country != null && "SUCCESS".equals(country.getString("msg"))) {
                Map twoMap = ((List<Map>) country.get("data")).get(0);
                subRequest.setParentIndexCode(twoMap.get("indexCode").toString());
                subRequest.setTreeCode(twoMap.get("treeCode").toString());
                String threeRes = subRegions(subRequest);
                JSONObject threeJson = JSONObject.parseObject(threeRes);
                if (country != null && "SUCCESS".equals(country.getString("msg"))) {
                    districtList = (List<Map>) threeJson.get("data");
                }
            }
        }
        return districtList;
    }


    /**
     * 根据父级DI 或局域名称模糊匹配
     * @param parentIndexCode
     * @param treeCode
     * @param name
     * @return
     */
    public static List<Map> getHikDistrictRes(String parentIndexCode, String treeCode, String name) {

        Map<String, Object> paramsMap = new HashMap<>();
        List<String> paramsList = new ArrayList<>();
        if(StringUtils.isNotBlank(parentIndexCode)){
            paramsList.add(parentIndexCode);
        }
        if(StringUtils.isNotBlank(name)){
            paramsMap.put("regionName", name);
        }
        paramsMap.put("pageNo", "1");
        paramsMap.put("pageSize", "1000");
        paramsMap.put("isSubRegion", "true");
        paramsMap.put("parentIndexCodes", paramsList);
        paramsMap.put("resourceType", "region");
        String resultResponse = nodesByParams(paramsMap);

        JSONObject resultObj = JSONObject.parseObject(resultResponse);
        List<Map> list = new ArrayList<>();
        if (resultObj != null && "SUCCESS".equals(resultObj.getString("msg"))) {
            List<Map> listMap = (List<Map>) resultObj.getJSONObject("data").get("list");
            for (Map childrenMap : listMap) {
                boolean leaf = (boolean) childrenMap.get("leaf");
                if (leaf) {
                    list.add(childrenMap);
                }
            }
        }
        return list;
    }


    //根据区域编号获取下级监控点列表--分页
    public static List<Map> getCameras(CamerasRequest camerasRequest) {
        List<Map> list = null;
        Jedis jedis = RedisUtil.getClient();
        ArtemisConfig.host = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret
        String camerasDataApi = "/artemis" + "/api/resource/v1/regions/regionIndexCode/cameras";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", camerasDataApi);
            }
        };
        String body = JSON.toJSONString(camerasRequest);
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject != null && "SUCCESS".equals(jsonObject.getString("msg"))) {
            JSONObject data_json = (JSONObject) jsonObject.get("data");
            list = (List<Map>) data_json.get("list");
        }
        return list;
    }


    public static void main(String[] args) {
//       List<Map> hikOrigin = getHikOrigin();
//       List<Map> hikOrigin = getHikOrigin();
//       System.out.println("huang====d=ddd==dd=====" + hikOrigin.toString());
        PreviewURLsRequest request = new PreviewURLsRequest();
        request.setCameraIndexCode("aae3b2a57df84c1ca49d3dbd98edab22");
        previewURLs(request);
        System.out.println("huang====d=ddd==dd=====" + request.toString());
    }

    //根据区域编号获取下一级区域列表
    public static String subRegions(SubRegionsRequest subRegionsRequest) {
        Jedis jedis = RedisUtil.getClient();
        ArtemisConfig.host = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret
        String subRegionsDataApi = "/artemis" + "/api/resource/v1/regions/subRegions";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", subRegionsDataApi);
            }
        };
        String body = JSON.toJSONString(subRegionsRequest);
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        System.out.println("huang====" + result);
        return result;
    }

    //查询区域列表v2
    public static String nodesByParams(Map<String, Object> map) {
        Jedis jedis = RedisUtil.getClient();
        ArtemisConfig.host = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret
        String subRegionsDataApi = "/artemis" + "/api/irds/v2/region/nodesByParams";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", subRegionsDataApi);
            }
        };
        String body = JSON.toJSONString(map);
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        return result;
    }


    // 获取监控点预览取流URL
    public static String previewURLs(PreviewURLsRequest previewURLsRequest) {
        Jedis jedis = RedisUtil.getClient();
        ArtemisConfig.host = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret
        String previewURLsDataApi = "/artemis" + "/api/video/v1/cameras/previewURLs";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", previewURLsDataApi);
            }
        };
        String body = JSON.toJSONString(previewURLsRequest);
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        return result;
    }

    // 获取监控点回放取流URL
    public static String playbackURLs(PlaybackURLsRequest playbackURLsRequest) {
        Jedis jedis = RedisUtil.getClient();
        ArtemisConfig.host = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret
        String playbackURLsDataApi = "/artemis" + "/api/video/v1/cameras/playbackURLs";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", playbackURLsDataApi);
            }
        };
        String body = JSON.toJSONString(playbackURLsRequest);
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, "application/json");
        return result;
    }

    // 手动录像
    public static String startManualRecord(String cameraIndexCode) {

        /**
         * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
         */
        Jedis jedis = RedisUtil.getClient();
        ArtemisConfig.host = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret

        /**
         * STEP3：设置接口的URI地址
         */
        final String getCamsApi = "/artemis" + "/api/video/v1/manualRecord/start";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);// 根据现场环境部署确认是http还是https
            }
        };

        /**
         * STEP4：设置参数提交方式
         */
        String contentType = "application/json";

        /**
         * STEP5：组装请求参数
         */
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("cameraIndexCode", cameraIndexCode);
        jsonBody.put("recordType", 6);
        jsonBody.put("type", 0);
        String body = jsonBody.toJSONString();

        /**
         * STEP6：调用接口
         */
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType, null);
        System.out.println(result);
        return result;
    }

    //获取手动录像状态
    public static String getManualRecordStatus(String taskID, String cameraIndexCode) {

        /**
         * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
         */
        //	ArtemisConfig.host = "116.31.123.84:89"; // artemis网关服务器ip端口
        Jedis jedis = RedisUtil.getClient();
        ArtemisConfig.host = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret

        /**
         * STEP2：设置OpenAPI接口的上下文
         */

        /**
         * STEP3：设置接口的URI地址
         */
        final String getCamsApi = "/artemis" + "/api/video/v1/manualRecord/status";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);// 根据现场环境部署确认是http还是https
            }
        };

        /**
         * STEP4：设置参数提交方式
         */
        String contentType = "application/json";

        /**
         * STEP5：组装请求参数
         */
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("cameraIndexCode", cameraIndexCode);
        jsonBody.put("taskID", taskID);
        jsonBody.put("type", 0);
        String body = jsonBody.toJSONString();

        /**
         * STEP6：调用接口
         */
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType, null);
        System.out.println(result);
        return result;
    }

    //停止手动录像
    public static String stopManualRecord(String taskID, String cameraIndexCode) {

        /**
         * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
         */
        Jedis jedis = RedisUtil.getClient();
        ArtemisConfig.host = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret

        /**
         * STEP2：设置OpenAPI接口的上下文
         */

        /**
         * STEP3：设置接口的URI地址
         */
        final String getCamsApi = "/artemis" + "/api/video/v1/manualRecord/stop";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);// 根据现场环境部署确认是http还是https
            }
        };

        /**
         * STEP4：设置参数提交方式
         */
        String contentType = "application/json";

        /**
         * STEP5：组装请求参数
         */
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("cameraIndexCode", cameraIndexCode);
        jsonBody.put("taskID", taskID);
        jsonBody.put("type", 0);
        String body = jsonBody.toJSONString();

        /**
         * STEP6：调用接口
         */
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType, null);
        System.out.println(result);
        return result;
    }

    //手动抓图
    public static String manualCapture(String cameraIndexCode) {

        /**
         * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
         */
        //ArtemisConfig.host = "116.31.123.84:89"; // artemis网关服务器ip端口
        Jedis jedis = RedisUtil.getClient();
        String HaiKanIp = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.host = HaiKanIp;
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret

        /**
         * STEP2：设置OpenAPI接口的上下文
         */

        /**
         * STEP3：设置接口的URI地址
         */
        final String getCamsApi = "/artemis" + "/api/video/v1/manualCapture";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);// 根据现场环境部署确认是http还是https
            }
        };

        /**
         * STEP4：设置参数提交方式
         */
        String contentType = "application/json";

        /**
         * STEP5：组装请求参数
         */
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("cameraIndexCode", cameraIndexCode);
        String body = jsonBody.toJSONString();

        /**
         * STEP6：调用接口
         */
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType, null);
        System.out.println(result);
        return result;
    }

    //获取视频事件的图片
    public static String getPicture(String picUri, String svrIndexCode) {

        /**
         * STEP1：设置平台参数，根据实际情况,设置host appkey appsecret 三个参数.
         */
        //ArtemisConfig.host = "116.31.123.84:89"; // artemis网关服务器ip端口
        Jedis jedis = RedisUtil.getClient();
        ArtemisConfig.host = jedis.get(AppConfig.REDIS + "HaiKanIp");
        ArtemisConfig.appKey = jedis.get(AppConfig.REDIS + "HaiKanKey"); // 秘钥appkey
        ArtemisConfig.appSecret = jedis.get(AppConfig.REDIS + "HaiKanSecret");// 秘钥appSecret

        /**
         * STEP2：设置OpenAPI接口的上下文
         */

        /**
         * STEP3：设置接口的URI地址
         */
        final String getCamsApi = "/artemis" + "/api/video/v1/events/picture";
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getCamsApi);// 根据现场环境部署确认是http还是https
            }
        };

        /**
         * STEP4：设置参数提交方式
         */
        String contentType = "application/json";

        /**
         * STEP5：组装请求参数
         */
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("svrIndexCode", svrIndexCode);
        jsonBody.put("picUri", picUri);
        jsonBody.put("netProtocol", "http");
        String body = jsonBody.toJSONString();

        /**
         * STEP6：调用接口
         */
        String result = ArtemisHttpUtil.doPostStringArtemis(path, body, null, null, contentType, null);
        System.out.println(result);
        return result;
    }


}
